# -*- coding: utf-8 -*-
"""
===============================
@Author     : Zuo WenTao
@Time       : 2024/10/30 14:27
@Description: 
@Change     : 
@File       : app.py
===============================
"""
import sys
import platform


if platform.system().lower() == 'linux':
    sys.path.append("/home/zuo/26_DocumentDelivery/")
from Api.BaseApi import create_md5
import time
import datetime
import uuid

from flask import Flask, jsonify, request
from loguru import logger

from Api.mongo_client import mongo_client2 as mongo_api

# try:
#     from Task.DocumentDelivery import DocumentDelivery
# except ImportError as e:
#     print(e)

app = Flask(__name__)
task_table = "DocumentDeliveryTask"


@app.route("/submit_task", methods=["GET"])
def down_submit():
    try:
        doi = request.args.get('doi')
        assert doi, "DOI 参数缺失！"

        logger.debug(f'任务提交: doi:{doi}')


        now_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        now_timestamp = int(time.time())

        search_res = mongo_api.find_document(col=task_table, query={'doi': doi})
        if search_res[1]:
            status = search_res[1].get('status')
            if status in [0, 1]:
                logger.debug(f'doi：{doi} 文献传递任务已存在，task_id:{search_res[1]["task_id"]}')
                return jsonify({"code": 200, "msg": "任务已存在！", 'data': {'task_id': search_res[1]['task_id'], "path": search_res[1]['local_file_path']}})
        task_id = create_md5(doi)

        insert_data = {
            'task_id': task_id if not search_res[0] else search_res[1]['task_id'],
            'status': 0,
            'create_date': now_date,
            'timestamp': now_timestamp,
            'update_date': now_date,
            'doi': doi,
            'local_file_path': "",
        }

        insert_status, insert_res = mongo_api.update_document(task_table, {"doi": doi}, {"$set": insert_data}, upsert=True)
        assert insert_status, "插入失败！"
        if not insert_status:
            return jsonify({"code": 400, "msg": f"任务处理失败", 'data': {'task_id': task_id}})
        logger.debug(f'DOI：{doi}任务传递成功 ，task_id:{task_id}')
        return jsonify({"code": 200, "msg": f"任务提交成功", 'data': {'task_id': task_id}})
    except AssertionError as e:
        logger.error(e)
        return jsonify({"code": 400, "error": e.__str__()}), 400
    except Exception as e:
        logger.error(f"未知错误：{e.__str__()}")
        return jsonify({"code": 400, "error": f"未知错误：{e.__str__()}"}), 400


@app.route("/check_task", methods=["GET"])
def down_query():
    try:
        task_id = request.args.get('task_id')
        assert task_id, "task_id 不可为空！"

        search_res = mongo_api.find_document(col=task_table, query={'task_id': task_id})
        assert search_res, "查询失败！"
        status = search_res[1]['status']
        if status == 0:
            return jsonify({"code": 301, "msg": '任务未开始'}), 301
        if status == 2:
            return jsonify({"code": 300, "msg": '文献传递中'}), 300
        elif status == 1:
            return jsonify({"code": 200, "msg": '文献传递已完成', "file_path": search_res[1]['local_file_path']}), 200
        elif status == -1:
            return jsonify({"code": 404, "msg": f'任务处理失败: {search_res[1]["error_msg"]}'}), 400
        elif status == -2:
            return jsonify({"code": 405, "msg": f'文献传递多次失败: {search_res[1]["error_msg"]}'}), 400
        else:
            return jsonify({"code": 400, "msg": '状态异常'}), 400
    except AssertionError as e:
        error = e.__str__()
        return jsonify({"code": 400, "msg": error}), 400
    except Exception as e:
        error = f"未知错误：{str(e)}"
        return jsonify({"code": 400, "msg": error}), 400


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
